/**
 * 
 */
package org.tio.sitexxx.view.http.pathmodel;

import java.util.Map;
import java.util.Objects;

import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.server.util.Resps;
import org.tio.sitexxx.service.model.main.Blog;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.base.UserRoleService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.conf.ConfService;
import org.tio.sitexxx.service.service.tiosite.BlogService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.view.annotaion.ModelGeneratorPath;
import org.tio.sitexxx.web.server.utils.WebUtils;
import org.tio.utils.json.Json;

import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.util.ObjectUtil;

/**
 * 查看某一篇博客
 * @author tanyaowu
 */
@ModelGeneratorPath({ Const.Path.BLOG_VIEW, Const.Path.DOC_TIO, Const.Path.DOC_TIO_SITE, Const.Path.BLOG_DATA })
public class BlogViewPathModelGenerator implements PathModelGenerator {

	/**
	 * 
	 */
	public BlogViewPathModelGenerator() {
	}

	@Override
	public HttpResponse generate(HttpRequest request, String path, Map<Object, Object> baseModel) throws Exception {
		Integer blogid = request.getInt("id");

		Integer initblogid = blogid;

		//当前用户可能是null
		User curr = WebUtils.currUser(request);

		//是否是文档页
		boolean isDoc = !Const.Path.BLOG_VIEW.equals(path);

		if (blogid == null) {
			blogid = ConfService.getInt("doc.default.id", 149);
			if (Const.Path.DOC_TIO_SITE.equals(path)) {
				blogid = 176;
			}
			initblogid = blogid;
//			if (isDoc) {
//				blogid = ConfService.getInt("doc.default.id", 149);
//				return Resps.redirect(request, "/doc/" + ConfService.getString("doc.default.id", "149"));
//			}
		}

		Record blog = BlogService.me.getByIdWithHtml(blogid);
		if (blog == null) {
			return ret404(request, path);
		}

		boolean isopen = ObjectUtil.equal(blog.get("open"), (byte) 1);

		Integer newblogid = blogid;
		if (isDoc) { //是文档页
			if (curr == null) {
				if (blogid != 163) {
					newblogid = 142; //没登录提醒页
				}
			} else {
				if (!isopen) {
					if (!UserRoleService.hasRole(curr, Const.Role.ALLOW_READ_DOC)) { //如果没有权限阅读文档
						newblogid = 138; //文档付费介绍页面
					}
				}
			}
		}
		if (!Objects.equals(newblogid, blogid)) {
			blog = BlogService.me.getByIdWithHtml(newblogid);
		}
		blogid = newblogid;

		if (blog != null) {
			Integer uid = blog.get("uid");//Uid();
			User user = UserService.ME.getById(uid); //博主

			if (!UserService.isSupper(curr)) { //超超管是啥都能看的
				//用户不存在，或状态不正常
				if (user == null || !UserRoleService.checkUserStatus(user)) {
					return ret404(request, path);
				}

				//当前用户和作者不是同一个人
				if (curr == null || ObjectUtil.notEqual(uid, curr.getId())) {
					//非公开 (非公开的可以在文档页看，但不允许直接通过博客查看)
					if (!isopen) {
						if (!isDoc) { //博客页
							return ret404(request, path);
						}
					}

					//草稿
					if (ObjectUtil.equal(Blog.Status.DRAFT, blog.get("status"))) {
						return ret404(request, path);
					}
				}

				//封停了
				if (ObjectUtil.equal(Blog.Status.SUSPENDED, blog.get("status"))) {
					return ret404(request, path);
				}
			}

			//保存访问日志
			Integer currid = null;
			if (curr != null) {
				currid = curr.getId();
			}
			BlogService.me.saveAccessLog(initblogid, blogid, request.getHttpSession().getId(), currid, request.getUserAgent(), request.getClientIp(), request.getReferer());

			String fromurl = blog.get("fromurl");
			baseModel.put(Const.ModelKey.TITLE, blog.get("title"));
			baseModel.put("html", blog.get("html"));
			baseModel.put("id", blogid);
			baseModel.put("nick", user.getNick());
			baseModel.put("uid", user.getId());
			baseModel.put("avatar", user.getAvatar());
			baseModel.put("createtime", blog.get("createtime"));
//			baseModel.put("open", ObjectUtil.equal(blog.get("open"), (byte) 1) ? "公开" : "私有");
//			baseModel.put("original", ObjectUtil.equal(blog.get("original"), (byte) 1) ? "原创" : "<a href='" + fromurl + "' target='_blank'>转载</a>");
			baseModel.put("open", blog.getInt("open"));
			baseModel.put("original", blog.getInt("original"));
			baseModel.put("fromurl", fromurl);
			baseModel.put("roles", Json.toJson(user.getRoles()));
			//			baseModel.put("accessCount", accessCount);

			//			blog.setMd(null);  //把md清空一下再放json
			//			baseModel.put("json", Json.toJson(baseModel));

		} else {
			return ret404(request, path);
		}

		return null;
	}

	private static HttpResponse ret404(HttpRequest request, String path) throws Exception {
		if (Const.Path.BLOG_DATA.equals(path)) {
			return Resps.forward(request, "/p400/400-without-header.html");
		} else {
			return Resps.resp404(request);
		}

	}

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}

}
